<?php
namespace App\Api\Controllers\Czbank;

use App\Api\Controllers\Config\CzbankPayConfigController;
use App\Api\Controllers\BaseController;
use App\Api\Controllers\WftPay\PayController as WftpayPayController;
use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\MerchantWalletDetail;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Models\UserWalletDetail;
use Illuminate\Support\Facades\Log;

class LogicController extends BaseController
{
    public function __construct()
    {

    }

    public function qrSubmitParams ($data_insert, $data)
    {
        $payConfig = new \App\Api\Controllers\Config\CzbankPayConfigController();
        $config = $payConfig->config($data['config_id']);
        if (!$config) {
            return json_encode([
                'status' => 2,
                'message' => '浙商支付配置不存在请检查配置'
            ]);
        }
        $merchant = $payConfig->czbank_merchant($data['store_id'], $data['store_pid']);
        if (!$merchant) {
            return json_encode([
                'status' => 2,
                'message' => '浙商支付商户号不存在'
            ]);
        }
        //支付宝
        if ($data['ways_type'] == '100002') {
            $out_trade_no = 'ali_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '支付宝';
            $data_insert['ways_source'] = 'alipay';
            $data_insert['ways_source_desc'] = '支付宝';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        //云闪付
        if ($data['ways_type'] == '100003') {
            $out_trade_no = 'un_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '银联支付';
            $data_insert['ways_source'] = 'unionpay';
            $data_insert['ways_source_desc'] = '银联支付';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        //微信
        if ($data['ways_type'] == '100001') {
            $out_trade_no = 'wx_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '微信支付';
            $data_insert['ways_source'] = 'weixin';
            $data_insert['ways_source_desc'] = '微信支付';
            $data_insert['out_trade_no'] = $out_trade_no;
        }

        $obj = new WftpayPayController();
        $data['mch_id'] = $merchant->mch_id;
        $data['out_trade_no'] = $out_trade_no;
        $data['body'] = $data['shop_name'];
        $data['total_amount'] = $data['total_amount'];
        $data['private_rsa_key'] = $config->private_rsa_key;
        $data['public_rsa_key'] = $config->public_rsa_key;
        $return = $obj->send_qr($data); //0-系统错误 1-成功 2-失败
        if ($return['status'] == 1) {
            $insert_re = $this->insert_day_order($data_insert);
            if (!$insert_re) {
                return json_encode([
                    'status' => 2,
                    'message' => '订单未入库'
                ]);
            }

            if (isset($return['data']['code_url']) && !empty($return['data']['code_url'])) {
                return json_encode([
                    'status' => 1,
                    'data' => ['codeUrl' => $return['data']['code_url']]
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => $return['message']
                ]);
            }
        } else {
            return json_encode([
                'status' => 2,
                'message' => $return['message']
            ]);
        }
//        $payData = [
//            "mch_id" => $merchant->mch_id,
//            "out_trade_no" => $out_trade_no,
//            "total_amount" => $data['total_amount'],
//            'key' => $merchant->key,
//        ];
//        $return = (new PayController())->qr_submit($payData, $config);
//        if ($return['status'] == 1) {
//            $insert_re = (new \App\Api\Controllers\BaseController())->insert_day_order($data_insert);
//            if (!$insert_re) {
//                return json_encode([
//                    'status' => 2,
//                    'message' => '订单未入库'
//                ]);
//            }
//            return json_encode([
//                'status' => 1,
//                'data' => $return['data']
//            ]);
//        } else {
//            return json_encode([
//                'status' => 2,
//                'message' => $return['message']
//            ]);
//        }
    }


    public function payParams ($data_insert, $data)
    {
        try {
            $store_id = $data['store_id'] ?? '';
            $store_pid = $data['store_pid'] ?? '';
            $merchant_id = $data['merchant_id'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $ways_type = $data['ways_type'] ?? '';
            $store_name = $data['store_name'] ?? '';
            $config_id = $data['config_id'] ?? '';
            $ways_type_desc = $data['ways_type_desc'] ?? '';
            $ways_source = $data['ways_source'] ?? '';
            $title = $data['title'] ?? '';
            $tg_user_id = $data['tg_user_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $code = $data['code'] ?? '';
            $company = $data['company'] ?? '';
            $ways_source_desc = $data['ways_source_desc'] ?? '';
            $device_id = $data['device_id'] ?? ''; //终端设备号.注:当中国银联时,为必填
            $data['goods_detail'] = $data['couponDetail'];
            $payConfig = new CzbankPayConfigController();
            $config = $payConfig->wftpay_config($config_id);

            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '浙商银行支付配置不存在请检查配置'
                ]);
            }

            $merchant = $payConfig->czbank_merchant($store_id, $store_pid);
            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '浙商银行支付商户号不存在'
                ]);
            }

            //入库参数
            $data_insert['out_trade_no'] = $out_trade_no;
            $data_insert['ways_type'] = $ways_type;
            $data_insert['ways_type_desc'] = $ways_type_desc;
            $data_insert['ways_source'] = $ways_source;
            $data_insert['company'] = $company;
            $data_insert['ways_source_desc'] = $ways_source_desc;

            $insert_re = $this->insert_day_order($data_insert);
            if (!$insert_re) {
                return json_encode([
                    'status' => 2,
                    'message' => '订单未入库'
                ]);
            }
            $obj = new WftpayPayController();
            $data['mch_id'] = $merchant->mch_id;
            $data['out_trade_no'] = $out_trade_no;
            $data['body'] = $title;
            $data['total_amount'] = $total_amount;
            $data['code'] = $code;
            $data['private_rsa_key'] = $config->private_rsa_key;
            $data['public_rsa_key'] = $config->public_rsa_key;
            $return = $obj->scan_pay($data); //0-系统错误 1-成功 2-失败
            if ($return['status'] == 0) {
                return json_encode([
                    'status' => 2,
                    'message' => $return['message']
                ]);
            }

            //返回支付成功
            if ($return['status'] == 1) {
                $trade_no = $return['data']['transaction_id']; //平台交易号
                $discount_amount=$return['data']['mdiscount']/100;
                $other_no = $return['data']['out_transaction_id']; //第三方订单号
                $buyer_user_id = $return['data']['buyer_user_id'] ?? ''; //	买家在支付宝的用户id
                $buyer_logon_id = $return['data']['buyer_logon_id'] ?? ''; //买家支付宝账号
                $pay_time = date('Y-m-d H:i:s', time());
                $buyer_pay_amount = $total_amount;
                $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');

                $update_data = [
                    'trade_no' => $trade_no,
                    'buyer_id' => $buyer_user_id,
                    'buyer_logon_id' => $buyer_logon_id,
                    'status' => '1',
                    'pay_status_desc' => '支付成功',
                    'pay_status' => 1,
                    'payment_method' => '', //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                    'pay_time' => $pay_time,
                    'buyer_pay_amount' => $buyer_pay_amount, //用户实际支付
                    'discount_amount' => $discount_amount
                ];
                $this->update_day_order($update_data, $out_trade_no);

                //支付成功后的动作
                $data = [
                    'ways_type' => $data['ways_type'],
                    'ways_type_desc' => $data['ways_type_desc'],
                    'company' => $data_insert['company'],
                    'source_type' => '100001', //返佣来源
                    'source_desc' => 'czbank', //返佣来源说明
                    'total_amount' => $total_amount,
                    'other_no' => $other_no,
                    'out_trade_no' => $out_trade_no,
                    'rate' => $data_insert['rate'],
                    'fee_amount' => $data_insert['fee_amount'],
                    'merchant_id' => $merchant_id,
                    'store_id' => $store_id,
                    'user_id' => $tg_user_id,
                    'config_id' => $config_id,
                    'store_name' => $store_name,
                    'ways_source' => $data['ways_source'],
                    'pay_time' => $pay_time,
                    'device_id' => isset($data['device_id']) ? $data['device_id'] : "",
                ];
                PaySuccessAction::action($data);

                return json_encode([
                    'status' => 1,
                    'pay_status' => '1',
                    'message' => '支付成功',
                    'data' => [
                        'out_trade_no' => $out_trade_no,
                        'ways_type' => $ways_type,
                        'total_amount' => $total_amount,
                        'store_id' => $store_id,
                        'store_name' => $store_name,
                        'config_id' => $config_id,
                        'pay_time' => $pay_time,
                        'trade_no' => $trade_no,
                        'ways_source' => $data['ways_source'],
                    ]
                ]);
            }

            //支付中
            if ($return['status'] == 3) {
                $trade_no = $return['data']['transaction_id']??""; //平台交易号
                return json_encode([
                    'status' => 1,
                    'pay_status' => 2,
                    'message' => $return['message'] ?? '支付中',
                    'data' => [
                        'trade_no' => $trade_no??"",
                        'out_trade_no' => $out_trade_no,
                        'ways_type' => $ways_type,
                        'ways_source' => $data['ways_source'],
                        'total_amount' => $total_amount,
                        'store_id' => $store_id,
                        'store_name' => $store_name,
                        'config_id' => $config_id,
                    ]
                ]);
            }

            //支付失败
            if ($return['status'] == 2) {
                return json_encode([
                    'status' => 2,
                    'pay_status' => 3,
                    'message' => $return['message'] ?? '支付失败',
                    'data' => [
                        'out_trade_no' => $out_trade_no,
                        'ways_type' => $ways_type,
                        'ways_source' => $data['ways_source'],
                        'total_amount' => $total_amount,
                        'store_id' => $store_id,
                        'store_name' => $store_name,
                        'config_id' => $config_id,
                    ]
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()
            ]);
        }
    }

    public function queryParams ($store_id, $store_pid, $data, $order)
    {
        try {
            $config_id = $data['config_id'] ?? '';
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $payConfig = new CzbankPayConfigController();
            $config = $payConfig->wftpay_config($config_id);

            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '浙商银行支付配置不存在请检查配置'
                ]);
            }

            $merchant = $payConfig->czbank_merchant($store_id, $store_pid);
            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '浙商银行支付商户号不存在'
                ]);
            }

            //支付状态为 退款中、已退款、有退款，退款查询接口
            $obj = new WftPayPayController();
            $cibpay_data = [
                'mch_id' => $merchant->mch_id,
                'out_trade_no' => $order->out_trade_no,
                'private_rsa_key' => $config->private_rsa_key,
                'public_rsa_key' => $config->public_rsa_key
            ];
            if ($order->pay_status == 5 || $order->pay_status == 6 || $order->pay_status == 7) {
                $return = $obj->refund_query($cibpay_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败

                //支付成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count'] -1; //退款记录数
                    $refund_no = $return['data']['out_refund_id_'.$refund_count] ?? $return['data']['out_refund_no_'.$refund_count]; //第三方退款单号or平台退款单号
                    $pay_time = isset($return['data']['refund_time_'.$refund_count]) ? date('Y-m-d H:i:s', strtotime($return['data']['refund_time_'.$refund_count])): ''; //退款时间,yyyyMMddHHmmss
                    $refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count]/100): $order->total_amount; //退款总金额,单位为分,可以做部分退款
                    $refund_amount = number_format($refund_amount, 2, '.', '');
                    $trade_no = $return['data']['out_transaction_id']; //第三方订单号

                    //改变数据库状态
                    if ($order->pay_status != 6) {

                        $insert_data = [
                            'status' => '6',
                            'pay_status' => 6,
                            'pay_status_desc' => '退款成功',
                            'refund_no' => $refund_no,
                            'refund_amount' => $refund_amount
                        ];
                        if ($pay_time) $insert_data['pay_time'] = $pay_time;
                        $this->update_day_order($insert_data, $order->out_trade_no);

                        //退款成功后的动作
                        $return_data = [
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $trade_no,
                            'store_id' => $order->store_id,
                            'merchant_id' => $order->merchant_id,
                            'type' => $order->ways_type,
                            'ways_source' => $order->ways_source,
                            'refund_amount' => $refund_amount,
                            'refund_no' => $refund_no
                        ];
                        RefundOrder::query()->create($return_data);
                        RefundSuccessAction::action([
                            'out_trade_no'=>$order->out_trade_no,
                            'refund_no' => $refund_no, //联动流水号
                        ]);
                    }

                    return json_encode([
                        'status' => '1',
                        'pay_status' => 6,
                        'message' => '退款成功',
                        'data' => [
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'out_trade_no' => $order->out_trade_no,
                            'refund_amount' => $refund_amount,
                            'total_amount' => $order->total_amount,
                            'other_no' => $other_no,
                            'trade_no' => $trade_no
                        ]
                    ]);
                }
                elseif($return['status'] == 2) {
                    return json_encode([
                        'status' => '2',
                        'pay_status' => '2',
                        'message' => '支付中',
                        'data' => [
                            'ways_source' => $order->ways_source,
                            'out_trade_no' => $order->out_trade_no,
                            'pay_amount' => $order->pay_amount,
                            'total_amount' => $order->total_amount
                        ]
                    ]);
                }
                else {
                    return json_encode([
                        'status' => '1',
                        'pay_status' => 3,
                        'message' => $return['message'],
                        'data' => [
                            'ways_source' => $order->ways_source,
                            'out_trade_no' => $order->out_trade_no,
                            'pay_amount' => $order->pay_amount,
                            'total_amount' => $order->total_amount
                        ]
                    ]);
                }
            } else {

                $return = $obj->order_query($cibpay_data); //0-系统错误 1-成功 2-失败 3-转入退款 4-未支付 5-已关闭 6-已冲正 7-已撤销 8-用户支付中

                //支付成功
                if ($return['status'] == 1) {
                    $pay_time = $return['data']['time_end'] ? date('Y-m-d H:i:s', strtotime($return['data']['time_end'])): ''; //支付完成时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010
                    $trade_no = $return['data']['transaction_id']; //平台交易号
                    $buyer_pay_amount = $return['data']['total_fee'] ? ($return['data']['total_fee']/100): ''; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['out_transaction_id'] ?? ''; //第三方交易号

                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            // 'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $order->out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '100001', //返佣来源
                            'source_desc' => '浙商银行', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    return json_encode([
                        'status' => '1',
                        'pay_status' => 1,
                        'message' => '支付成功',
                        'data' => [
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'out_trade_no' => $order->out_trade_no,
                            'pay_amount' => $buyer_pay_amount,
                            'total_amount' => $order->total_amount,
                            'other_no' => $other_no,
                            'trade_no' => $trade_no
                        ]
                    ]);
                }
                elseif($return['status'] == 2) {
                    return json_encode([
                        'status' => '2',
                        'pay_status' => '3',
                        'message' => '支付失败',
                        'data' => [
                            'ways_source' => $order->ways_source,
                            'out_trade_no' => $order->out_trade_no,
                            'pay_amount' => $order->pay_amount,
                            'total_amount' => $order->total_amount
                        ]
                    ]);
                }
                elseif($return['status'] == 8) {
                    return json_encode([
                        'status' => '1',
                        'pay_status' => '2', //1-成功 2-支付中
                        'message' => '用户支付中',
                        'data' => [
                            'ways_source' => $order->ways_source,
                            'out_trade_no' => $order->out_trade_no,
                            'pay_amount' => $order->pay_amount,
                            'total_amount' => $order->total_amount
                        ]
                    ]);
                }
                else {
                    return json_encode([
                        'status' => '1',
                        'pay_status' => 3,
                        'message' => $return['message'],
                        'data' => [
                            'out_trade_no' => $order->out_trade_no,
                            'pay_amount' => $order->pay_amount,
                            'total_amount' => $order->total_amount
                        ]
                    ]);
                }
            }
         } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()
            ]);
        }
    }

    public function refundParams($data, $order)
    {
        try {
            $merchant_id = $data['merchant_id'];
            $out_trade_no = $data['out_trade_no'];
            $refund_amount = isset($data['refund_amount']) ?  floatval($data['refund_amount']): 0.00;
            $refund_no = isset($data['refund_no']) ? $data['refund_no'] : $out_trade_no . '123';
            if ($refund_no == "") {
                $refund_no = time();
            }

            $ways_type = $order->ways_type;
            $store_id = $order->store_id;
            $refund_amount = isset($refund_amount) && $refund_amount ? $refund_amount : ($order->buyer_pay_amount ? $order->buyer_pay_amount: ($order->receipt_amount ?$order->receipt_amount:$order->pay_amount));

            $store = Store::where('store_id', $store_id)
                ->select('config_id', 'merchant_id', 'pid', 'is_before_refund')
                ->first();
            $config_id = $store->config_id;
            $store_id = $order->store_id;
            $store_pid = $store->pid;
            $other_no = $order->other_no;
            $out_trade_no = $order->out_trade_no;
            $total_amount = $order->total_amount; //交易总额
            $trade_no = $order->trade_no;
            $rate = $order->rate; //订单但是费率
            $new_refund_amount = $order->refund_amount + $refund_amount; //总退款
            $new_fee_amount = ($total_amount - $new_refund_amount) * ($rate/100); //退款后的手续费

            $payConfig = new CzbankPayConfigController();
            $config = $payConfig->wftpay_config($config_id);

            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '浙商银行支付配置不存在请检查配置'
                ]);
            }

            $merchant = $payConfig->czbank_merchant($store_id, $store_pid);
            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '浙商银行支付商户号不存在'
                ]);
            }

            $cibpay_return_data = [
                'mch_id' => $merchant->mch_id,
                'out_trade_no' => $out_trade_no,
                'total_amount' => $total_amount,
                'refund_fee' => $refund_amount,
                'private_rsa_key' => $config->private_rsa_key,
                'public_rsa_key' => $config->public_rsa_key
            ];

            $obj = new WftPayPayController();
            $return = $obj->refund($cibpay_return_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败

            //退款请求成功
            if ($return['status'] == '1') {
                $refund_count = $return['data']['refund_count']-1; //退款记录数
                $insert_data = [
                    'status' => '6',
                    'pay_status' => 6,
                    'pay_status_desc' => '已退款',
                    'refund_amount' => $new_refund_amount,
                    'fee_amount' => $new_fee_amount
                ];
                $this->update_day_order($insert_data, $out_trade_no);

                RefundOrder::create([
                    'ways_source' => $order->ways_source,
                    'type' => $ways_type,
                    'refund_amount' => $refund_amount, //退款金额
                    'refund_no' => $return['data']['refund_id_'.$refund_count], //平台退款单号
                    'store_id' => $store_id,
                    'merchant_id' => $merchant_id,
                    'out_trade_no' => $out_trade_no,
                    'trade_no' => $trade_no
                ]);

                //返佣去掉
                UserWalletDetail::where('out_trade_no', $out_trade_no)->update([
                    'settlement' => '03',
                    'settlement_desc' => '退款订单'
                ]);
                MerchantWalletDetail::where('out_trade_no', $out_trade_no)->update([
                    'settlement' => '03',
                    'settlement_desc' => '退款订单'
                ]);

                $data = [
                    'refund_amount' => $refund_amount,
                    'out_trade_no' => $out_trade_no,
                    'refund_no' => $return['data']['refund_id_'.$refund_count], //平台退款单号
                    'other_no' => $other_no
                ];
                return json_encode([
                    'status' => '1',
                    'message' => '退款成功',
                    'data' => $data
                ]);
            } //退款处理中
            elseif($return['status'] == '3') {
                $insert_data = [
                    'status' => '5',
                    'pay_status' => 5,
                    'pay_status_desc' => '退款中'
                ];
                $this->update_day_order($insert_data, $out_trade_no);
                $refund_count = $return['data']['refund_count']-1; //退款记录数
                $data = [
                    'refund_amount' => $refund_amount,
                    'out_trade_no' => $out_trade_no,
                    'refund_no' => $return['data']['refund_id_'.$refund_count], //平台退款单号
                    'other_no' => $other_no
                ];
                return json_encode([
                    'status' => '1',
                    'message' => '退款中',
                    'data' => $data
                ]);
            }
            else {
                //其他情况
                $message = $return['message'];
                return json_encode([
                    'status' => '2',
                    'message' => $message
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()
            ]);
        }
    }

    public function refundQueryParams()
    {
        return [];
    }



}
